package com.example.entity;

import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;

import java.util.*;

/**
 * @Description
 * @Date 2022/4/13 14:08
 * @Created by Klein
 */
public class ListUtils {

    public static <T> List<List<T>> getSplitList(List<T> list, int n) {

        if (list == null) {
            throw new NullPointerException("List is null.");
        }

        if (n <= 0) {
            throw new IllegalArgumentException();
        }

        List<List<T>> groupList = Lists.newArrayList();
        List<T>  newList = Lists.newArrayList(list);

        int len = newList.size();
        int num = len % n == 0 ? len / n : (len / n + 1);

        for (int i = 0; i < num; i++) {
            groupList.add(list.subList(i * n, (i+1) * n > len ? len : (i+1) * n  ));
        }

        return groupList;

    }
    public static <S, T> List<T> copyList(List<S> sources,  Class<T> target) {
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T t = null;
            try {
                t =target.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }

            BeanUtils.copyProperties(source, t);
            list.add(t);
        }
        return list;
    }

    public static Object[][] convertTo2DArrayWithoutHeader(List<Map<String, Object>> data, List<String> xNameList) {
        if (data == null) {
            return new Object[0][0];
        }

        List<List<Object>> resultData = new ArrayList<>();
//
//        for (String s : xNameList) {
//
//        }

        for (Map<String, Object> datum : data) {

            List<Object> dataItem = new ArrayList<>();
            for (String s : xNameList) {
                dataItem.add(datum.get(s));
            }

            resultData.add(dataItem);
        }

        return convertTo2DArraySafely(resultData);
    }

    public static Object[][] convertTo2DArraySafely(List<List<Object>> list) {
        if (list == null) {
            return new Object[0][0];
        }

        Object[][] array = new Object[list.size()][];

        for (int i = 0; i < list.size(); i++) {
            List<Object> subList = list.get(i);
            array[i] = subList == null ? null : subList.toArray(new Object[0]);
        }

        return array;
    }



}
